package com.gnerv.battle.rabbitmq.agent.tool;

import lombok.Data;
import org.springframework.util.ObjectUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author Gnerv LiGen
 */
public class ExecTools {

    private ExecTools() {
    }

    public static ExecResult run(List<String> commandList, String directory) {
        return run(commandList, new File(directory));
    }

    public static ExecResult run(List<String> commandList, File directory) {
        ProcessBuilder processBuilder = new ProcessBuilder(commandList);
        processBuilder.redirectErrorStream(true);
        if (!ObjectUtils.isEmpty(directory)) {
            processBuilder.directory(directory);
        }
        ExecResult execResult = new ExecResult();
        try {
            Process process = processBuilder.start();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String stdout = readStream(bufferedReader);
            execResult.setStdout(stdout);
            execResult.setStatus(process.waitFor());
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        return execResult;
    }

    public static ExecResult run(String command, File directory) {
        Runtime runtime = Runtime.getRuntime();
        ExecResult execResult = new ExecResult();
        try {
            Process process = runtime.exec(command, null, directory);
            BufferedReader bufferedReaderInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String stdout = readStream(bufferedReaderInput);
            execResult.setStdout(stdout);
            BufferedReader bufferedReaderError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String stderr = readStream(bufferedReaderError);
            execResult.setStderr(stderr);
            execResult.setStatus(process.waitFor());
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
        return execResult;
    }

    private static String readStream(BufferedReader bufferedReader) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        String builderString = stringBuilder.toString();
        return StringTools.removeColorCharacters(builderString);
    }


    @Data
    public static class ExecResult {
        private int status;
        private String stdout;
        private String stderr;
    }

}
